<?php

declare(strict_types=1);

namespace App\Controller;

use App\Model\ChatRecord;
use App\Model\FriendGroup;
use App\Model\Friend;
use App\Model\GroupMember;
use App\Model\Group;
use App\Model\SystemMessage;
use App\Model\User;

use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\View\RenderInterface;

/**
 * @Controller()
 * Class ChatUserController
 * @package App\Controller
 */
class ChatUserController extends AbstractController
{
    /**
     * @Inject()
     * @var \Hyperf\Contract\SessionInterface
     */
    private $session;


    /**
     * @Inject()
     * @var RenderInterface
     */
    protected $render;

    public function index(RequestInterface $request, ResponseInterface $response)
    {
        return $response->raw('Hello Hyperf!');
    }


    /**
     * @GetMapping(path="userinfo")
     *  初始化用户信息
     */
    public function userinfo()
    {
        $token = $this->request->input('token');


        $user = RedisLib::getInstance()->get('User_token_' . $token, $default = null);

        if (!$user) {
            return $this->response->json([
                "code" => 10001,
                "data" => '',
                "msg"  => '获取用户信息失败'
            ]);
        }

        $user = json_decode($user, true);


        $groups = GroupMember::where('user_id', $user['id'])->get();


        $friend_groups = FriendGroup::where('user_id', $user['id'])
            ->select('id', 'groupname')
            ->get();

        foreach ($friend_groups as $k => $v) {
            $friend_groups[$k]['list'] = Friend::where('friend.user_id', $user['id'])
                ->where('friend_group_id', $v['id'])
                ->get();
        }

        $data = [
            'mine'   => [
                'username' => $user['nickname'] . '(' . $user['id'] . ')',
                'id'       => $user['id'],
                'status'   => $user['status'],
                'sign'     => $user['sign'],
                'avatar'   => $user['avatar']
            ],
            "friend" => $friend_groups,
            "group"  => $groups
        ];
        return $this->response->json([
            "code" => 0,
            "data" => $data,
            "msg"  => 'success'
        ]);
    }

    /**
     *  查找页面
     */
    public function find()
    {
        $params = $this->request()->getRequestParam();

        $type       = isset($params['type']) ? $params['type'] : '';
        $wd         = isset($params['wd']) ? $params['wd'] : '';
        $user_list  = [];
        $group_list = [];
        $key        = '%' . $wd . '%';
        switch ($type) {
            case "user" :
                $user_list = User::create()
                    ->where([
                        'id'       => [$key, 'like', 'or'],
                        'nickname' => [$key, 'like', 'or'],
                        'username' => [$key, 'like', 'or'],
                    ])
                    ->field('id,nickname,avatar')
                    ->all(null, true);
                break;
            case "group" :
                $group_list = Group::create()
                    ->where([
                        'id'        => [$key, 'like', 'or'],
                        'groupname' => [$key, 'like', 'or'],
                    ])->field('id,groupname,avatar')
                    ->all(null, true);
                break;
            default :
                break;
        }

        $this->render('find', ['user_list' => $user_list, 'group_list' => $group_list, 'type' => $type, 'wd' => $wd]);
    }

    /**
     *  加入群
     */
    public function joinGroup()
    {
        $params = $this->request()->getRequestParam();
        $token  = $params['token'];

        $RedisPool = Redis::defer('redis');
        $user      = $RedisPool->get('User_token_' . $token);

        if (!$user) {
            return $this->responseJson(10001, "获取用户信息失败");
        }
        $user = json_decode($user, true);


        $id   = $params['groupid'];
        $isIn = GroupMember::create()->where('group_id', $id)->where('user_id', $user['id'])->get();


        if ($isIn) {
            return $this->responseJson(10001, "您已经是该群成员");
        }
        $group = Group::create()->where('id', $id)->get();
        $res   = GroupMember::create()->data(['group_id' => $id, 'user_id' => $user['id']])->save();
        if (!$res) {
            return $this->responseJson(10001, "加入群失败");
        }
        $data = [
            "type"      => "group",
            "avatar"    => $group['avatar'],
            "groupname" => $group['groupname'],
            "id"        => $group['id']
        ];
        return $this->responseJson(200, "加入成功", $data);
    }


    /**
     * 创建群
     */
    public function createGroup()
    {
        if ($this->request()->getMethod() == 'POST') {
            $params = $this->request()->getRequestParam();
            $token  = $params['token'];

            $RedisPool = Redis::defer('redis');
            $user      = $RedisPool->get('User_token_' . $token);

            if (!$user) {
                return $this->responseJson(10001, "获取用户信息失败");
            }

            $user = json_decode($user, true);

            $data = [
                'groupname' => $params['groupname'],
                'user_id'   => $user['id'],
                'avatar'    => $params['avatar']
            ];

            $group_id = Group::create()->data($data)->save();

            $res_join = GroupMember::create()->data(['group_id' => $group_id, 'user_id' => $user['id']])->save();
            if ($group_id && $res_join) {
                $data = [
                    "type"      => "group",
                    "avatar"    => $params['avatar'],
                    "groupname" => $params['groupname'],
                    "id"        => $group_id
                ];
                return $this->responseJson(200, "创建成功！", $data);
            } else {
                return $this->responseJson(10001, "创建失败！");
            }
        } else {
            $this->render('create_group');

        }
    }

    /**
     *   获取群成员
     */
    public function groupMembers()
    {
        $params = $this->request()->getRequestParam();


        $id   = $params['id'];
        $list = GroupMember::create()->alias('gm')
            ->join('`user` as u', 'u.id=gm.user_id')
            ->where('group_id', $id)
            ->field('u.username,u.id,u.avatar,u.sign')->all(null, true);

        if (!count($list)) {
            return $this->responseJson(10001, "获取群成员失败");
        }
        return $this->responseJson(0, "", ['list' => $list]);
    }

    /**
     * 聊天记录
     */
    public function chatLog()
    {
        $limit = 20;
        if ($this->request()->getMethod() == 'POST') {
            $params = $this->request()->getRequestParam();
            $token  = $params['token'];

            $RedisPool = Redis::defer('redis');
            $user      = $RedisPool->get('User_token_' . $token);

            if (!$user) {
                return $this->responseJson(10001, "获取用户信息失败");
            }

            $user = json_decode($user, true);

            $id   = $params['id'];
            $type = $params['type'];
            $page = $params['page'];


            if ($type == 'group') {
                ChatRecord::create()->alias('cr')
                    ->join('`user` as u', 'u.id = cr.user_id')
                    ->field('u.nickname as username,u.id,u.avatar,time as timestamp,cr.content');


                $list   = ChatRecord::create()
                    ->alias('cr')
                    ->join('`user` as u', 'u.id = cr.user_id')
                    ->where('cr.group_id', $id)
                    ->order('time', 'DESC')
                    ->field('u.nickname as username,u.id,u.avatar,time as timestamp,cr.content')
                    ->limit($limit * ($page - 1), $limit)->withTotalCount();
                $result = $list->lastQueryResult();

                // 总条数
                $total = $result->getTotalCount();

                $count = ceil($total / $limit);
                // 列表数据
                $list = $list->all(null, true);

            } else {
                $list = ChatRecord::create()
                    ->alias('cr')
                    ->join('`user` as u', 'u.id = cr.user_id')
                    ->where('cr.user_id', $user['id'])
                    ->where('cr.friend_id', $id)
                    ->where([
                        'cr.user_id' => [$id, 'like', 'or'],
                    ])
                    ->where('cr.friend_id', $user['id'])
                    ->order('time', 'DESC')
                    ->field('u.nickname as username,u.id,u.avatar,time as timestamp,cr.content')
                    ->limit($limit * ($page - 1), $limit)->withTotalCount()->all(null, true);

            }
            foreach ($list as $k => $v) {
                $list[$k]['timestamp'] = $v['timestamp'] * 1000;
            }
            $list['data']      = $list;
            $list['last_page'] = empty($count) ? 0 : $count;
            return $this->responseJson(0, '', $list);
        } else {
            $params = $this->request()->getRequestParam();

            $id   = $params['id'];
            $type = $params['type'];
            $this->render('chat_log', ['id' => $id, 'type' => $type]);

        }
    }

    /**
     * @GetMapping(path="loginout")
     * 退出登录
     */
    public function loginout()
    {
        $token = $this->request->input('token');
        RedisLib::getInstance()->del('User_token_' . $token);

        return $this->render->render('login');
    }

    /**
     * 消息盒子
     */
    public function messageBox()
    {
        $params = $this->request()->getRequestParam();
        $token  = $params['token'];

        $RedisPool = Redis::defer('redis');
        $user      = $RedisPool->get('User_token_' . $token);

        if (!$user) {
            return $this->responseJson(10001, "获取用户信息失败");
        }


        $user = json_decode($user, true);
        SystemMessage::create()->where('user_id', $user['id'])->update(['read' => 1]);


        $list = SystemMessage::create()
            ->alias('sm')
            ->join('`user` as f', 'f.id = sm.from_id')
            ->where('user_id', $user['id'])
            ->order('id', 'DESC')
            ->field('sm.id,f.id as uid,f.avatar,f.nickname,sm.remark,sm.time,sm.type,sm.group_id,sm.status')
            ->all(null, true);


        foreach ($list as $k => $v) {
            $list[$k]['time'] = $this->__time_tranx($v['time']);
        }

        $this->render('message_box', ['list' => $list]);
    }

    private function __time_tranx($the_time)
    {
        $now_time = time();
        $dur      = $now_time - $the_time;
        if ($dur <= 0) {
            $mas = '刚刚';
        } else {
            if ($dur < 60) {
                $mas = $dur . '秒前';
            } else {
                if ($dur < 3600) {
                    $mas = floor($dur / 60) . '分钟前';
                } else {
                    if ($dur < 86400) {
                        $mas = floor($dur / 3600) . '小时前';
                    } else {
                        if ($dur < 259200) { //3天内
                            $mas = floor($dur / 86400) . '天前';
                        } else {
                            $mas = date("Y-m-d H:i:s", $the_time);
                        }
                    }
                }
            }
        }
        return $mas;
    }

    /**
     * 添加好友
     */
    public function addFriend()
    {
        $params = $this->request()->getRequestParam();
        $token  = $params['token'];
        $id     = $params['id'];

        $RedisPool = Redis::defer('redis');
        $user      = $RedisPool->get('User_token_' . $token);

        if (!$user) {
            return $this->responseJson(10001, "获取用户信息失败");
        }


        $system_message = SystemMessage::create()->where('id', $id)->findOne();

        $isFriend = Friend::create()->where('user_id', $system_message['user_id'])
            ->where('friend_id', $system_message['from_id'])->findOne();

        if ($isFriend) {
            return $this->responseJson(10001, '已经是好友了');
        }

        $data = [
            [
                'user_id'         => $system_message['user_id'],
                'friend_id'       => $system_message['from_id'],
                'friend_group_id' => $params['groupid']
            ],
            [
                'user_id'         => $system_message['from_id'],
                'friend_id'       => $system_message['user_id'],
                'friend_group_id' => $system_message['group_id']
            ]
        ];
        foreach ($data as $item => $value) {
            $res = Friend::create()->data($value)->save();
        }


        if (!$res) {
            return $this->responseJson(10001, '添加失败');
        }
        SystemMessage::create()->where('id', $id)->update(['status' => 1]);
        $user = User::create()->where('id', $system_message['from_id'])->findOne();


        $data = [
            "type"     => "friend",
            "avatar"   => $user['avatar'],
            "username" => $user['nickname'],
            "groupid"  => $params['groupid'],
            "id"       => $user['id'],
            "sign"     => $user['sign']
        ];

        $system_message_data = [
            'user_id' => $system_message['from_id'],
            'from_id' => $system_message['user_id'],
            'type'    => 1,
            'status'  => 1,
            'time'    => time()
        ];
        SystemMessage::create()->data($system_message_data)->save();

        return $this->responseJson(200, '添加成功', $data);
    }

    /**
     * 拒绝添加好友
     */
    public function refuseFriend()
    {
        $params = $this->request()->getRequestParam();

        $id = $params['id'];


        $system_message = SystemMessage::create()->where('id', $id)->findOne();

        $res = SystemMessage::create()->where('id', $id)->update(['status' => 2]);

        $data = [
            'user_id' => $system_message['from_id'],
            'from_id' => $system_message['user_id'],
            'type'    => 1,
            'status'  => 2,
            'time'    => time()
        ];
        $res1 = SystemMessage::create()->data($data)->save();

        if ($res && $res1) {
            return $this->responseJson(200, "已拒绝");
        } else {
            return $this->responseJson(10001, "操作失败");
        }
    }
}
